﻿using System;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Web;
using InfoJetSoft.Service.Entity;
using Microsoft.Deployment.Compression.Cab;
using Microsoft.Deployment.Compression;

namespace InfoJetSoft.Service.Util
{
	//CAB文件解码器，将CAB中的文件读取到Manifest中。
	class CABDecoder {

		public static void doFDI( HttpContext context, InfoJetContext jetContext, Manifest manifest) 
        {
			// Erucy: Remove Local Load
            //如果正在从目录加载（从DataFlow调用），直接读取目录内的文件。
            //if( manifest.XSNConfig.IsLoadingFromFolder )
            //{
            //    DirectoryInfo dirInfo = new DirectoryInfo( manifest.XSNConfig.Folder );
            //    loadAllCABFiles( dirInfo, manifest );
            //}
            ////反之，先将XSN Binary内容写到磁盘上，再解压缩。
            //else
            //{
                ////查看是否存在TempFolder配置.
                ////CID 0315 //2009.06.12 //Begin
                //string extractFolder = ConfigUtil.TempFolder();
                ////CID 0315 //2009.06.12 //End
                //string cabinetFullPath = null;
			
                ////使用一个GUID作为临时文件名.
                //Guid guid = Guid.NewGuid();
                //if( extractFolder == null )
                //{
                //    //如果不存在,使用系统临时目录.
                //    cabinetFullPath = Path.GetTempPath() + guid.ToString() + ".xsn";
                //}
                //else
                //{
                //    //如果存在则使用指定目录.
                //    cabinetFullPath = extractFolder + "\\" + guid.ToString() + ".xsn"; 
                //}
                ////将XSN内容写到临时文件中.
                //FileStream fileStream = File.OpenWrite( cabinetFullPath );
                //fileStream.Write( manifest.XSNConfig.Content , 0 , manifest.XSNConfig.Content.Length );
                //fileStream.Close();

                ////创建目录，用来存放解压缩的文件。
                //DirectoryInfo dirInfo = Directory.CreateDirectory( cabinetFullPath + ".dir" );
			
                ////使用SetupAPI.dll解压缩。
                //if( ConfigUtil.SetupAPIExtract() )
                //{
                //    SetupAPIExtractor extractor = new SetupAPIExtractor();
                //    extractor.CabPath = cabinetFullPath;
                //    extractor.TargetPath = dirInfo.FullName;
                //    extractor.Extract();
                //}
                //    //使用extrac32.exe解压缩。
                //else
                //{
                //    string extracLine = "/Y /E /L \"" + dirInfo.FullName + "\" \"" + cabinetFullPath + "\"";
                //    ProcessStartInfo startInfo = new ProcessStartInfo( "extrac32.exe", extracLine );
                //    startInfo.CreateNoWindow = false;
                //    startInfo.UseShellExecute = false;
                //    Process extrac32 = Process.Start( startInfo );
                //    extrac32.WaitForExit();
                //}

                ////将解压缩出的文件加载到Manifest中。
                //loadAllCABFiles( dirInfo, manifest );

                ////删除临时文件。
                //if( ConfigUtil.DeleteTemplateFiles() )
                //{
                //    try
                //    {
                //        File.Delete( cabinetFullPath );
                //    }
                //    catch( Exception e )
                //    {
                //    }
                //}

            // Erucy : Extract by CabLib / Wix
            //Extract ext = new Extract();
            //using (MemoryStream ms = new MemoryStream(manifest.XSNConfig.Content))
            //{
            //    manifest.CabFileList = new ArrayList();
            //    ext.evAfterCopyFile += (string s_File, byte[] u8_ExtractMem) =>
            //    {
            //        CABFile cabFile = new CABFile();
            //        cabFile.Name = Path.GetFileName(s_File);
            //        cabFile.ByteOutput = u8_ExtractMem;
            //        manifest.CabFileList.Add(cabFile);
            //    };
            //    ext.ExtractStream(ms, "MEMORY");
            //}
            using (CabEngine engine = new CabEngine())
            {
                using (MemoryStream ms = new MemoryStream(manifest.XSNConfig.Content))
                {
                    manifest.CabFileList = new ArrayList();
                    foreach (ArchiveFileInfo fileInfo in engine.GetFileInfo(ms))
                    {
                        CABFile cabFile = new CABFile();
                        cabFile.Name = fileInfo.Name;
                        using (MemoryStream ss = engine.Unpack(ms, fileInfo.FullName) as MemoryStream)
                        {
                            cabFile.ByteOutput = ss.GetBuffer();
                        }
                        manifest.CabFileList.Add(cabFile);
                    }
                }
            }

				//CID 0103 //2008.08.26 //Begin
				if( jetContext != null )
				{
					jetContext.OnTemplateFilesReadyEvent( manifest );					
				}
				//CID 0103 //2008.08.26 //End
				
				//如果没有设置ResourceFolderName,说明未作ResourceCache的处理,仍然使用FormResourceCopier拷贝资源.
				if( manifest.ResourceFolderName == null )
				{
					//将CAB中的资源文件拷贝到Web服务器目录。
                    //CID 0618 //2010.06.28 //Begin
					FormResourceCopier.copyResource( context, jetContext, manifest );
                    //CID 0618 //2010.06.28 //End
				}
		}

        //Erucy Remove
        //private static void loadAllCABFiles( DirectoryInfo dirInfo, Manifest manifest )
        //{
        //    ArrayList cabFileList = new ArrayList();
			
        //    string[] files = Directory.GetFiles( dirInfo.FullName, "*.*" );
        //    foreach(string file in files)
        //    {
        //        FileStream fileStream = File.OpenRead( file );
        //        byte[] content = new byte[ (int)fileStream.Length ];
        //        fileStream.Read( content, 0, content.Length );
        //        fileStream.Close();
        //        CABFile cabFile = new CABFile();
        //        cabFile.Name = Path.GetFileName( file );
        //        cabFile.TempFile = file;
        //        cabFile.ByteOutput = content;
        //        cabFileList.Add( cabFile );
        //    }

        //    manifest.Folder = dirInfo.FullName;
        //    manifest.CabFileList = cabFileList;
        //}
	
	}
	
}